package DFS;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * Lettcode 417: https://leetcode-cn.com/problems/pacific-atlantic-water-flow/
 *
 * 可用于很好地理解dfs
 */
public class pacificAtlantic {
    private int m, n;
    private int[][] matrix;
    private int[][] direction = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}};

    public List<List<Integer>> pacificAtlantic(int[][] matrix) {
        List<List<Integer>> res = new ArrayList<>();
        if (matrix == null || matrix.length == 0) return res;
        m = matrix.length;
        n = matrix[0].length;
        boolean[][] canReachP = new boolean[m][n];
        boolean[][] canReachA = new boolean[m][n];
        for (int i = 0; i < m; i++) {
            dfs(matrix, canReachP, i, 0);
            dfs(matrix, canReachA, i, n - 1);
        }

        for (int i = 0; i < n; i++) {
            dfs(matrix, canReachP, 0, i);
            dfs(matrix, canReachA, n - 1, i);
        }

        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if (canReachA[i][j] && canReachP[i][j]) {
                    res.add(Arrays.asList(i, j));
                }
            }
        }
        return res;
    }

    private void dfs(int[][] matrix, boolean[][] canReach, int i, int j) {
        if (canReach[i][j]) return;
        canReach[i][j] = true;
        for (int[] d: direction) {
            int nextI = i + d[0];
            int nextJ = j + d[1];
            if (nextI < 0 || nextI >= m || nextJ < 0 || nextJ >= n || matrix[nextI][nextJ] < matrix[i][j]) {
                continue;
            }
            dfs(matrix, canReach, nextI, nextJ);
        }
    }
}
